<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/11/27
 * Time: 12:00
 * 绑定菜单（菜单授权） bind_menu.php
 */
namespace app\appmenu\controller;

use app\common\helper\appmenu_helper;
use app\common\model\Appmenu;
use app\common\model\Company;
use app\common\model\OpenCard;
use app\common\model\Setting;
use think\facade\View;
use think\facade\Request;
use app\admin\controller\AdminBase;

class BindMenu extends AdminBase
{
    protected $appmenu_key = array();

    public function initialize()
    {
        parent::initialize();
        $this->open_card_id = OpenCard::get_open_card_id();
        $this->company_id   = Company::get_company_id();
        $appmenu_key        = Setting::get_setting_info('appmenu_key');
        if ($appmenu_key) {
            $this->appmenu_key = unserialize($appmenu_key);
        }
    }

    public function __call($action = '', $params = array())
    {
        return View::fetch('bind_menu', [
            'info' => $this->appmenu_key
        ]);
    }

    public function save()
    {
        $appid     = Request::param('appid', '');
        $appsecret = Request::param('appsecret', '');

        $info = array();
        if (!$appid) {
            return _return('AppId不能为空');
        }
        if (!$appsecret) {
            return _return('AppSecret不能为空');
        }

        $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
        // 如果$access_token不存在, 则请求接口
        $access_token = appmenu_helper::get_access_token($token_url);
        if (!$access_token) {
            Setting::update_setting_info('appmenu_key', '', $this->open_card_id, $this->company_id);
            return _return('获取凭证失败，请检查appid和appsecret或稍后尝试');
        }

        $info['access_token'] = $access_token;
        $info['appid']        = $appid;
        $info['appsecret']    = $appsecret;

        Setting::update_setting_info('appmenu_key', serialize($info), $this->open_card_id, $this->company_id);

        return redirect(url('/appmenu/admin/index'));
        //return array('授权成功', 'success', AnUrl('appmenu/controller'));
    }
}